import Icon from '@/components/Icon'
import Input from '@/components/Input'
import NavBar from '@/components/NavBar'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import styles from './index.module.scss'
import io from 'socket.io-client'
import { getTokenInfo } from '@/utils/storage'
import { getUser } from '@/store/actions/profile'

const Chat = () => {
	const [messageList, setMessageList] = useState([
		// 放两条初始消息
		{ type: 'robot', text: '亲爱的用户您好，小智同学为您服务。' },
		{ type: 'user', text: '你好' },
	])
	const [msg, setMsg] = useState('')

	const clientRef = useRef(null)
	const listRef = useRef(null)

	const photo = useSelector((state) => state.profile.user.photo)

	const dispatch = useDispatch()
	// socket的连接
	useEffect(() => {
		// 发送请求获取图片信息
		dispatch(getUser())

		// 1. 建立连接
		const client = io('http://toutiao.itheima.net', {
			query: {
				token: getTokenInfo().token,
			},
			transports: ['websocket'],
		})

		// 由于要在不同函数中使用, 因此保存一份到clientRef中
		clientRef.current = client

		// client.on() 监听事件
		// client.emit() 主动给服务端发送消息
		client.on('connect', () => {
			setMessageList([
				...messageList,
				{
					type: 'robot',
					text: '我是小智, 你有什么想问我的吗',
				},
			])
		})

		client.on('message', function (e) {
			setMessageList((messageList) => {
				return [
					...messageList,
					{
						type: 'robot',
						text: e.msg,
					},
				]
			})
		})

		return () => client.close()
	}, [dispatch])

	// 监听滚动条
	useEffect(() => {
		// scrollTop滚动的大小, scrollHeight带滚动的盒子的高度, offsetHeight盒子的高度(带边框), clientHeight内容的可视区高度(不带边框)
		listRef.current.scrollTop = 
			listRef.current.scrollHeight - listRef.current.offsetHeight
	}, [messageList])

	const onKeyUp = (e) => {
		if (e.keyCode !== 13) return
		if (!msg) return

		setMessageList([
			...messageList,
			{
				type: 'user',
				text: msg,
			},
		])

		clientRef.current.emit('message', {
			msg,
			timestamp: Date.now(),
		})
		// 清空消息
		setMsg('')
	}

	return (
		<div className={styles.root}>
			{/* 顶部导航栏 */}
			<NavBar className="fixed-header">小智同学</NavBar>

			{/* 聊天记录列表 */}
			<div className="chat-list" ref={listRef}>
				{/* 机器人的消息 */}
				{messageList.map((item, index) => {
					if (item.type === 'robot') {
						return (
							<div key={index} className="chat-item">
								<Icon type="iconbtn_xiaozhitongxue" />
								<div className="message">{item.text}</div>
							</div>
						)
					} else {
						return (
							<div key={index} className="chat-item user">
								<img
									src={
										photo ||
										'http://toutiao.itheima.net/images/user_head.jpg'
									}
									alt=""
								/>
								<div className="message">{item.text}</div>
							</div>
						)
					}
				})}
			</div>

			{/* 底部消息输入框 */}
			<div className="input-footer">
				<Input
					className="no-border input"
					placeholder="请描述您的问题"
					value={msg}
					onChange={(e) => setMsg(e.target.value)}
					onKeyUp={onKeyUp}
				/>
				<Icon type="iconbianji" />
			</div>
		</div>
	)
}

export default Chat
